package com.dbh.io.nio;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.escape.Html4Escape;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;

/**
 * @author dongbanghui
 * @date 2020/10/9
 */
public class IOUtil {

    public static void copyFile(String src, String dist) throws IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dist);

        byte[] buffer = new byte[20 * 1024];
        while (in.read(buffer, 0, buffer.length) != -1){
            out.write(buffer);
        }

        in.close();
        out.close();

    }

    public static void fastCopy(String src, String dist) throws IOException {
        //获得源文件的输入字节流
        FileInputStream fin = new FileInputStream(src);

        //获取输入字节流的文件通道
        FileChannel fcin = fin.getChannel();

        //获取目标文件的输出字节流
        FileOutputStream fout = new FileOutputStream(dist);

        //获取输出字节流的通道
        FileChannel fcout = fout.getChannel();

        //为缓冲区分配1024个字节
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while (true) {

            //从输入通道中读取数据到缓冲区中
            int r = fcin.read(buffer);

            //read()返回-1表示EOF
            if (r == -1){
                break;
            }

            //切换读写
            buffer.flip();

            //把缓冲区的内容写入输出文件中
            fcout.write(buffer);

            //清空缓冲区
            buffer.clear();
        }
    }

    public static void main(String[] args) throws IOException {
     /*   List<String> strings = FileUtil.readLines("/Users/dongbanghui/work/file/ip.txt", "UTF-8");


        String[] split = strings.get(0).split(",");
        for (String str : split){
            if (str.endsWith("11.65.166.162")){
                System.out.println(str.endsWith("11.65.166.162"));
            }
        }*/

        // 最简单的HTTP请求，可以自动通过header等信息判断编码，不区分HTTP和HTTPS
//        String result1= HttpUtil.get("https://get.jd.com/#/survey/index?id=40123&amp%3Berp=type");

        // 当无法识别页面编码的时候，可以自定义请求页面的编码
        String result2= HttpUtil.get("https://get.jd.com/#/survey/index?id=40123&amp%3Berp=type", CharsetUtil.CHARSET_UTF_8);

        FileUtil.writeBytes(result2.getBytes(), new File("/Users/dongbanghui/work/file/temp.log"));


        System.out.println(result2);
    }

}
